<?php
// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
use app\common\validate\Shop as ShopValidate;


class Shop extends Model
{
	
	//隐藏字段
	protected $hidden = ["guid",'is_del','is_enable','time','update_user','update_time','add_time'];
	
	//关联商品分类，一对多关联
	public function goodsCate(){
        return $this->hasMany('goods_cate','shop_id');
    }
	//关联商品模型，一对多关联
	public function goods(){
        return $this->hasMany('goods','shop_id');
    }
    //获取对应商品模型
	public function getGoodsModel(){
        return model('goods')->getModel();
    }
	//关联新品商品模型，一对多关联
	public function goodsNew(){
        return $this->hasMany('goods','shop_id');
	}
	//关联动态商品模型，一对多关联
	public function dynamicHasMany(){
        return $this->hasMany('goods','shop_id');
	}
	//关联秒杀模型，一对多关联
	public function goodsSeckill(){
        return $this->hasMany('goodsSeckill','shop_id');
	}
	//关联用户模型，一对多关联
	public function user(){
        return $this->hasOne('user','id','uid');
    }
	//关联用户点赞模型，一对多关联
	public function userStars(){
        return $this->hasMany('userStars','shop_id');
    }
	//关联订单模型，一对多关联
	public function order(){
        return $this->hasMany('order','shop_id');
    }
	//关联预览模型，一对多关联
	public function history(){
        return $this->hasMany('goodsHistory','shop_id');
    }
    //关联店员，一对多关联
	public function staff(){
        return $this->hasMany('shop_staff','shop_id');
    }
    
    //获取店铺详情
	public function getRemarkAttr($value){
        return htmlspecialchars_decode( $value ?: '' );
    }
    
    //关联用户账单表，一对多
	public function shopBill(){
        return $this->hasMany('ShopBill','shop_id','id');
    }
	
	/**
    * 搜店铺
    * @return type
    */
	public function search($where=[],$pageIndex=1,$pageSize=20)
    {
    	$model = new self;
		$model = $model->where($where);
		$model = $model->where('is_del',0);
		$model = $model->where('status',1);
		$model = $model->where('is_enable',1);
		$model = $model->field('id,name,img');
		$model = $model->page($pageIndex,$pageSize);
		$model = $model->order('add_time desc');
		$result = $model->all();
		
		foreach ($result as $key => $query) {
			$goods = $query->goods()
				->where('is_del',0)
				->where('status',1)
				->field('id,name,img,sale_price')
				->page(1,3)
				->select();
			$query['goods']=$goods;	
		}
		
		return $result;
    }
	
	
	
	/**
     * 添加店铺
     * @param type $uid
     * @return type
     */
	public function addShop($param)
    {
		//验证
    	$validate = new ShopValidate;
        if ( !$validate->check($param) ) {
        	throw new \think\Exception($validate->getError());
        }
		
		$model = new self;
		
		if( $model->where("uid", $param['uid'] )->where("status",'<>','-1')->where("is_del",'0')->find() ){
			throw new \think\Exception("当前用户已存在店铺，无须添加！");
		}
		
		if( $model->where("phone",$param['phone'])->where("status",'<>','-1')->where("is_del",'0')->find() ){
			throw new \think\Exception("该手机已存在店铺，无须添加！");
			return false;
		}
		
		$shop = $model->where("uid",$param['uid'])->where("status",'-1')->find();
		$shop = $shop ?: $model->where("uid",$param['uid'])->where("is_del",'1')->find();
		$shop = $shop ?: $model->where("phone",$param['phone'])->where("status",'-1')->find();
		$shop = $shop ?: $model->where("phone",$param['phone'])->where("is_del",'1')->find();
		
		if($shop){
			$param['status'] = 0;
			$param['is_del'] = 0;
			$model ->allowField(true) -> save($param,['id'=>$shop['id']]);
		}else{
			$model ->allowField(true) -> save($param);
		}
		
		return true;
    }
	
	/**
     * 获取店铺信息
     * @param type $id
     * @return type
     */
	public function getShopInfo($id)
    {
    	$model = new self;
		$model = $model->with(['staff'=>function($query) {
			$query->where('is_del',0);
			$query->where('status',1);
			$query->field('id,shop_id,name,img,phone,work_type,sex,entry_time');
			$query->withAvg(['evaluate'=>function($query){
			    $query->where('is_del',0)->field('staff_id,service_score');
			    return 'star';
			}],'service_score');
			$query->withCount(['yyOrder'=>function($query){
			    $query->where('is_del',0);
			    return 'order_count';
			}]);
			$query->order('is_good,sort_no');
		}]);
		$model = $model->where('id', $id);
		$model = $model->field('is_del,sort_no,is_show,is_enable',true);
		return$model->find();
    }
	
	
	/**
     * 获取用户店铺信息
     * @param type $uid
     * @return type
     */
	public function getUserShopInfo($uid)
    {
    	$model = new self;
		$model = $model->where('uid', $uid);
		$model = $model->with(['goodsCate'=>function($query) {
			$query->where('is_show',1);
			$query->where('is_del',0);
			$query->field('id,name,shop_id');
		}]);
		$model = $model->where('is_del', 0);
		$model = $model->where('status', 1);
		$model = $model->order('sort_no','desc');
		$model = $model->field('is_del,sort_no,is_show',true);
		return$model->find();
    }
	
	/**
     * 获取店员店铺信息
     * @param type $uid
     * @return type
     */
	public function getStaffShopInfo($staffId)
    {
    	$model = new self;
		$model = $model->where('id', model('shop_staff')->where('id',$staffId)->value('shop_id') );
		$model = $model->where('is_del', 0);
		$model = $model->where('status', 1);
		$model = $model->order('sort_no','desc');
		$model = $model->field('is_del,sort_no,is_show,is_enable',true);
		return$model->find();
    }
	
	/**
     * 获取店铺账单
     * @param type $sid
     * @return type
     */
	public function getShopBill($sid)
    {
		$shop = self::where('id', $sid)->find();
		$result = model("ShopBill")->getShopBill($sid);
		$result['balance'] =  (float)($shop['balance']);
		$result['lock_balance'] =  (float)($shop['lock_balance']);
		$result['extract_cost'] =  (float)getSystem('buess_shop_extract_cost');
		$result['extract_min'] =  (float)getSystem('buess_shop_extract_min');
		return $result;
    }
	
	/**
     * 获取用户店铺账单
     * @param type $uid
     * @return type
     */
	public function getUserShopBill($uid)
    {
    	$model = new self;
		$shop = $model->where('uid', $uid)->find();
		$result = model("ShopBill")->getShopBill($shop['id']);
		$result['balance'] =  (int)($shop['balance']);
		$result['lock_balance'] =  (int)($shop['lock_balance']);
		$result['extract_cost'] =  (float)getSystem('buess_shop_extract_cost');
		$result['extract_min'] =  (float)getSystem('buess_shop_extract_min');
		return $result;
    }
	

	/**
     * 获取附近商家
     * @param type $uid
     * @return type
     */
	public function getNearbyShop($slat,$slng,$shop_id='',$name='',$cate_id=0,$p1=1,$p2=20)
    {
		$model = new self; 
		$model = $model->where('status',1);
		$model = $model->where('is_del',0);
		$model = $model->where('is_enable',1);
		$model = $model->where('id','<>',$shop_id);
		$model = $model->where('name','like',"%$name%");
		if($cate_id){ $model = $model->where('cate_id',$cate_id); }
		$model = $model->pages($p1,$p2);
		$model = $model->field('is_del,is_enable,sort_no,balance,lock_balance,is_show',true);
		$model = $model->field("ROUND(
	        6378.138 * 2 * 10000 * ASIN(
	            SQRT(
	                POW( SIN( ( $slat * PI() / 180 - latitude * PI() / 180 ) / 2 ),2) 
	                + COS( $slat * PI() / 180) * COS(latitude * PI() / 180) 
	                * POW( SIN(  ( $slng * PI() / 180 - longitude * PI() / 180 ) / 2), 2)
	            )
	        ) / 10000
	  	,1) as distance");
		return $model->select();
    }
    
    
   	 /**
     * TODO 订单收入
     */
    public static function orderIncome($id,$order)
    {
    	$key = $order['order_no'];
    	$pay_price = $order['pay_price'];
    	$bro = $order['brokerage'];
    	$use_offline_price = $order['use_offline_price'];
    	
    	if( $pay_price<=0 ){ return true; }
    		
    	$sr =  round($pay_price - $use_offline_price - $bro,2);
    	
    	$title =  '订单收入';
		$msg = ('订单收入' . round($pay_price,2) . '元，')
					.($use_offline_price ? '线下支付'.round($use_offline_price,2) .'元，' : '')
					.('分出'.round($bro,2) .'元佣金，');
					
		$shop = self::get($id);
	
		if($sr>0){
			$msg = $msg.('钱包收入'.$sr.'元！');
			if( $shop->shopBill()->income($title,$id,'balance','gain',$sr,$key,$shop['balance'],$msg,$bro) ){
				$shop->balance = ['inc', $sr];
				return $shop->save();
			}
		}else{
			$msg = $msg.('钱包支出'.(-$sr).'元！');
			if($shop->shopBill()->expend($title,$id,'balance','gain',(-$sr),$key,$shop['balance'],$msg,$bro)){
				$shop->balance = ['dec', (-$sr)];
				return $shop->save();
			}
		}

		throw new \think\Exception('店铺订单收入异常错误!');
    }
	
	
	/**
     * 获取最近预览商家
     * @param type $uid
     * @return type
     */
	public function latelyPreview($uid)
    {
		$model = new self; 
		$model = $model->alias('a');
		$model = $model->join('goods_history b','a.id = b.shop_id');
		$model = $model->where('a.status',1);
		$model = $model->where('a.is_del',0);
		$model = $model->where('b.uid',$uid);
		$model = $model->field('a.id,a.name,a.contacts,a.phone,a.address,a.address_detail');
		$model = $model->field('a.latitude,a.longitude,a.service_start_time,a.service_end_time');
		$model = $model->field('a.img,a.bgimg');
		$model = $model->field('b.see_time as preview_time');
		$model = $model->order('b.see_time', 'desc');
		$model = $model->group('a.id');
		$model = $model->limit(0,10);
		return $model->select();
    }
	


	/**
     * 获取店铺营业额
     * @param type $uid
     * @return type
     */
	public function turnover($shop_id,$date='')
    {
		$w[] = ['shop_id','=',$shop_id];
		$w[] = ['is_del','=',0];
		$w[] = ['is_pay','<>',0];
		
		$t = $date ?: date("Y-m-d");
		$field = 'pay_price';
		
		//按天
		$result['today'] =  model('Order')->where($w)
			->where('add_time','like',"%$t%")
			->sum($field);
		//昨天
		$result['yesterday'] =   model('Order')->where($w)
			->whereTime('add_time','yesterday')
			->sum($field);
		//本月	
		$result['month'] =  model('Order')->where($w)
			->whereTime('add_time','month')
			->sum($field);
		//上月		
		$result['last_month'] =  model('Order')->where($w)
			->whereTime('add_time','last month')
			->sum($field);	
		//本周
		$result['week'] =  model('Order')->where($w)
			->whereTime('add_time','week')
			->sum($field);	
		//上周		
		$result['last_week'] =  model('Order')->where($w)
			->whereTime('add_time','last week')
			->sum($field);		
			
		//	本周详情
		$result['week_data'] = model('Order')->where($w)
			->whereTime("add_time",'>','-7 days')
			->field("DATE_FORMAT(add_time,'%m-%d') as date")
			->field("sum($field) as price")
			->group("DATE_FORMAT(add_time,'%Y-%m-%d')")
			->select();	
		foreach ($result['week_data'] as $key => $row) {
			if($key == 0){
				$yesterday = $result['yesterday'];
			}else{
				$yesterday = $result['week_data'][$key-1]['price'];
			}
			$row['yesterday'] = $yesterday;
			$row['up'] = round(($row['price'] - $yesterday) / $yesterday,2).'%';
		}
		
		//返回
		return $result;
    }
	
	
	/**
     * 访客量
     * @param type $uid
     * @return type
     */
	public function visitor($shop_id)
    {
		$w[] = ['shop_id','=',$shop_id];
		
		//今天
		$result['today'] =  model('GoodsHistory')->where($w)
			->whereTime('see_time','d')
			->count();
		//昨天
		$result['yesterday'] =  model('GoodsHistory')->where($w)
			->whereTime('see_time','yesterday')
			->count();
		//总数	
		$result['count'] =  model('GoodsHistory')->where($w)->count();	
	
		//	本周详情
		$result['week_data'] = model('GoodsHistory')->where($w)
			->whereTime('see_time','>','-7 days')
			->field("DATE_FORMAT(see_time,'%m-%d') as date")
			->field("count(*) as count")
			->group("DATE_FORMAT(see_time,'%Y-%m-%d')")
			->select();	
		
		//返回
		return $result;
    }
	
}
